package com.android.fragmentdemo.definedrawable
import android.content.Context
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.CornerPathEffect
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.Log
import androidx.core.content.res.ResourcesCompat
import com.android.fragmentdemo.R

class DefineDrawable(context: Context) : Drawable() {

    private val mContext = context

    private var mAlpha = 0xFF

    private val rect by lazy {
        Rect()
    }

    private val paint by lazy {
        Paint().apply {
            isDither = true
            isAntiAlias = true
            color = ResourcesCompat.getColor(mContext.resources, R.color.color_C70CE6, null)
            pathEffect = CornerPathEffect(mContext.resources.getDimension(R.dimen.dp_10))
        }
    }

    override fun onBoundsChange(bounds: Rect) {
        super.onBoundsChange(bounds)
        if (bounds.right - bounds.left > 0 && bounds.bottom - bounds.top > 0) {
            rect.set(
                bounds.left,
                bounds.top,
                bounds.right,
                bounds.bottom
            )
            invalidateSelf()
        }
    }

    override fun onStateChange(stateArr: IntArray): Boolean {
        var stated = false
        for (state in stateArr) {
            when (state) {
                android.R.attr.state_pressed -> {
                    stated = true
                    break
                }
                android.R.attr.state_selected -> {
                    stated = true
                    break
                }
                android.R.attr.state_checked -> {
                    stated = true
                    break
                }
            }
        }

        if (stated) {
            Log.d(TAG, "pressed---true")
            paint.color = ResourcesCompat.getColor(mContext.resources, R.color.color_55C70CE6, null)
        } else {
            Log.d(TAG, "pressed---false")
            paint.color = ResourcesCompat.getColor(mContext.resources, R.color.color_55C70CE6, null)
        }

        invalidateSelf()

        return super.onStateChange(state)
    }

    override fun draw(canvas: Canvas) {
        canvas.drawRect(rect, paint)
    }

    override fun isStateful(): Boolean {
        return true
    }

    override fun setAlpha(alpha: Int) {
        if (alpha != mAlpha) {
            mAlpha = alpha
            invalidateSelf()
        }
    }

    override fun setColorFilter(colorFilter: ColorFilter?) {}

    @Deprecated(
        "Deprecated in Java",
        ReplaceWith("PixelFormat.TRANSLUCENT",
            "android.graphics.PixelFormat")
    )
    override fun getOpacity(): Int {
        return PixelFormat.TRANSLUCENT
    }

    companion object {
        const val TAG = "DefineDrawable"
    }
}